/**
 * Created by dengtao on 17/08/04.v0.0.1
 */
$(function () {
    var obj_ = {
        hasProtoType: false,
        runCheck: function () {
            if (this.hasProtoType == false) {
                this.hasProtoType = true;
                this.init.prototype = obj_;
            }
            return this.init();
        },

        shopListMonitor: function (srcel) {
            var self_ = obj_;
            var el = $('.shoplist-title');
            var ell = $('.shoplist-title-fixed-block');
            if (ell && ell.length > 0) {
                var coords = ell[0].getBoundingClientRect();

                if (coords.top < self_.nativeTitleHeight) {
                    el.css({
                        "position": "fixed",
                        "z-index": "999999",
                        "top": self_.nativeTitleHeight + 'px',
                        "clear": "both"
                    });
                } else {
                    el.css({"position": "absolute", "z-index": "999999", "top": "0", "clear": "both"});
                }

            }

            if (srcel.type == 'scroll' || srcel == 'onscroll') {

                //console.log($(this).scrollTop() + '-' + $('body')[0].offsetHeight);


                if (($(this).scrollTop() + 1 >= ($('body')[0].offsetHeight - $(this).height())) && !self_.isRequest) {
                    self_.isRequest = true;
                    console.log('要到底了');
                    self_.pageNum++;

                    self_.getShopList();
                }
            }


        },
        runSlide: function () {
            if (typeof Swiper != 'undefined') {
                obj_.swiperTopBanner = new Swiper('.slide-banner', {
                    pagination: '.swiper-pagination',
                    /* paginationClickable: true,
                     autoplay: 3000,
                     loop: true,*/
                    touchAngle: 60,
                    slidesPerView: 1,
                    paginationClickable: true,
                    loop: true,
                    autoplay: 3000,
                    autoplayDisableOnInteraction: false
                });

                obj_.swiperShopItem = new Swiper('#wh-item', {
                    slidesPerView: 'auto',
                    freeModeMomentumRatio: 0.9,
                    freeModeMomentumVelocityRatio: 1,
                    freeMode: true,
                });
            }


            //自动吸附顶部标题需after一个fixed元素
            $('body').after('<div style="width: 0;height: 0;position: fixed;top: 0;left:0;z-index:1;"></div>');
            document.addEventListener('touchmove', obj_.shopListMonitor, false);

            if (document.addEventListener) {
                window.addEventListener('scroll', obj_.shopListMonitor, false);
            } else {
                window.attachEvent('onscroll', obj_.shopListMonitor);
            }
        },
        runEvent: function () {
            var self_ = this;
            var sortType = '', sortType_ = '', sortArrowList = ['https://app.shopin.cn/cms/cmsfile/img/sortArrowUp@2.png', 'https://app.shopin.cn/cms/cmsfile/img/sortArrowUp@2.png', 'https://app.shopin.cn/cms/cmsfile/img/sortArrowDown@2.png']
                , backflag = null;

            $('.shoplist-title>div').on('click', function () {
                var $that = $(this);


                if ($that.hasClass('Bytime')) {
                    sortType = '1';
                    console.log('按时间');
                } else if ($that.hasClass('Bynum')) {
                    sortType = '3';
                    console.log('按销量');
                } else if ($that.hasClass('Byprice')) {
                    sortType = '2';
                    console.log('按价格');
                }


                $that.addClass('r-red').siblings().removeClass('r-red');
                sortType_ = (sortType == backflag && sortType_ == 2) ? 1 : 2;

                $that.siblings().find('img').prop('src', sortArrowList[2]);
                if ($that.find('img').length) {
                    $that.find('img').prop('src', sortArrowList[sortType_]);
                }


                if ($that.hasClass('recommend')) {
                    console.log('推荐');
                    sortType = '';
                    sortType_ = '';
                }


                backflag = sortType;
                self_.sortType = sortType + sortType_;
                console.log(self_.sortType);
                self_.pageNum = 1;

                self_.serverEnd = false;
                self_.getShopList(1);

            });

        },
        getUserLoginInfo: function () {
            WebViewJsBridge.getUserLoginInfo(null, function (data) {
                //alert('用户memberSid：' + JSON.parse(data).memberSid);
                if (data && JSON.parse(data).memberSid) {
                    localStorage.userMemberSid = JSON.parse(data).memberSid;
                }
            });
        },
        getShopList: function (isReload) {
            var self_ = this;
            var ajaxData = {"pageNum": self_.pageNum, "pageSize": (self_.pageSize + 1), "sortType": self_.sortType};

            if (localStorage.getItem('shopid') && self_.getPageName()[0].indexOf('index') == -1) {
                ajaxData.shopId = localStorage.getItem('shopid');
                //alert(JSON.stringify(ajaxData));
            }

            tools.doAjax(JSON.stringify(ajaxData), config.interface.getShopList, function (data) {
                var shopListObj = [];
                var serverEnd = '';

                console.log('请求了第' + self_.pageNum + '页');

                if (self_.serverEnd) {
                    return;
                }
                if (data && data.data && data.data.esProducts.length <= self_.pageSize) {
                    console.log('这是最后一页');
                    self_.serverEnd = true;
                    serverEnd = '<div style="line-height: 1rem;width: 100%;text-align: center;font-size: 14px;background: #fff;clear: both;padding-top: 0.3rem;">已经全部加载完毕</div>';
                    self_.pageNum--;
                } else {
                    data.data.esProducts.length = self_.pageSize;
                }


                $(data.data.esProducts).each(function (i, v) {
                    shopListObj.push('<div class="si-block" gonative="');
                    shopListObj.push(config.shopInfoUrl);
                    shopListObj.push('?productSid=');
                    shopListObj.push(v.productSid);
                    shopListObj.push('&supplySid=');
                    shopListObj.push(v.supplySid);
                    shopListObj.push('"><img data-echo="');

                    shopListObj.push(config.imgUrl);
                    shopListObj.push(v.proPictDir);
                    shopListObj.push(v.proPictName);

                    shopListObj.push('" class="si-shopimg" src="');

                    shopListObj.push('https://app.shopin.cn/cms/cmsfile/img/160x160.jpg');


                    shopListObj.push('"><div class="si-shopname">');


                    shopListObj.push('【');
                    shopListObj.push((Number(v.offValue) * 10).toFixed(1));
                    shopListObj.push(' 折】');


                    shopListObj.push(v.productName);


                    shopListObj.push('</div><div class="si-shopp"><span>￥</span>');
                    shopListObj.push(v.cuPrice.toFixed(2));

                    shopListObj.push('<span class="originalPrice"><span>￥</span>');
                    shopListObj.push(v.originalPrice);
                    shopListObj.push('</span>');

                    shopListObj.push('</div></div>');
                });
                if (isReload) {
                    //alert('清空再加载');
                    $('.shop-item').html('');
                }
                $('.shop-item').html($('.shop-item').html() + shopListObj.join(''));


                $('.shop-item').html($('.shop-item').html() + serverEnd);


                //解除重复请求限制
                self_.isRequest = false;

                //新增元素后必须的操作
                //给新增元素做懒加载
                Echo.init({
                    offset: 200,
                    throttle: 0
                });

                //绑定对原生的交互
                WebViewJsBridge.goNativeEvent();


            }, function () {
                console.log('异常了');
            }, function () {

            });
            Echo.init({
                offset: 150,
                throttle: 0
            });
        },
        getPageName: function () {
            var a = location.href;
            var b = a.split("/");
            var c = b.slice(b.length - 1, b.length).toString(String).split(".");
            return c.slice(0, 1);
        },
        updatePrice: function () {//根据商品ID获取并更新商品价格
            var sidDomList = $('[getpricebysid]');
            var sidAry = [];
            sidDomList.each(function (i, v) {
                //20170804
                //sidAry.push($(v).attr('getpricebysid'));
                sidAry.push($.trim($(v).attr('getpricebysid')));
            });
            console.log(sidAry.join());

            tools.doAjax({}, config.interface.getCmsShopListPriceBySid + sidAry.join(), function (data) {
                //console.log(data);
                $(data.data).each(function (c, p) {
                    console.log(p);
                    $('.sid' + p.productSid + ' .cuPrice').html('￥' + p.cuPrice);
                    $('.sid' + p.productSid + ' .originalPrice').html('￥' + p.originalPrice);
                    $('.sid' + p.productSid + ' .offValue').html(Number((p.offValue) * 10).toFixed(1) + '折');
                });

            });
        },
        init: function () {
            var self_ = this;

            self_.i = 0;//滑动计数
            self_.slideSwitch = false;
            self_.pageNum = 1;
            self_.pageSize = 20;
            self_.sortType = '';
            self_.isRequest = false;//是否正在请求
            self_.serverEnd = false;//数据列表页是否无数据

            self_.updatePrice();

            self_.runSlide();
            self_.runEvent();

            setTimeout(function () {
                self_.getUserLoginInfo();
            }, 150);


            self_.getShopList();


            //alert('宽度：' + $('body')[0].offsetWidth);
            ////获取native标题栏高度
            setTimeout(function () {
                self_.getUserLoginInfo();
                /**
                 WebViewJsBridge.getViewHeight({}, function (data) {
                    //alert(Number(JSON.parse(data).statusBarHeight) + Number(JSON.parse(data).titleBarHeight));
                    self_.nativeTitleHeight = Number(JSON.parse(data).statusBarHeight) + Number(JSON.parse(data).titleBarHeight);
                    //alert(self_.nativeTitleHeight);

                });*/
            }, 100);

            //native标题栏高度
            self_.nativeTitleHeight = tools.parseUrlParams(window.location.href).height;
            self_.nativeTitleHeight = typeof self_.nativeTitleHeight == 'undefined' ? 0 : self_.nativeTitleHeight;

            //alert(self_.nativeTitleHeight);

            Echo.init({
                offset: 200,
                throttle: 0
            });

        }
    };
    obj_.runCheck();
});